#ifndef TEXTLINECOMPOSER_H
#define TEXTLINECOMPOSER_H

template <typename CharType>
class TextLineComposer
{
public:
    virtual ~TextLineComposer() {}

    class TextLine
    {
    public:
        ~TextLine() { if(composer != NULL) composer->flush(); }

        TextLine(const TextLine &other) : composer(other.composer) {
            other.composer = NULL;
        }

        TextLine & operator = (const TextLine &other) {
            composer = other.composer;
            other.composer = NULL;
        }

        template <typename T>
        TextLine & operator << (const T &obj) {
            if (composer != NULL && composer->m_active) {
                composer->m_buffer << CharType(' ') << obj;
            }
            return *this;
        }

        template <typename T>
        TextLine & operator << (T & (*func)(T &)) {
            if (composer != NULL && composer->m_active) {
                composer->m_buffer << func;
            }
            return *this;
        }

        TextLine & operator << (const QString &s) {
            if (composer != NULL && composer->mActive) {
                printQString(composer->mBuffer, s);
            }
            return *this;
        }
    private:
        friend class TextLineComposer;
        TextLine(TextLineComposer *c) : composer(c) {}
        mutable TextLineComposer *composer;
    };

protected:
    TextLineComposer(bool active) : m_active(active) {}
    void setActive(bool v) { m_active = v; }

    virtual void printLine(const std::basic_string<CharType> &msg) = 0;

private:
    bool m_active;
    std::basic_ostringstream<CharType> m_buffer;

    void flush()
    {
        printLine(m_buffer.str());
        m_buffer.str(std::basic_string<CharType>());
    }

    static void printQString(std::basic_ostringstream<char> &c, const QString &s) {
        c << " " << s.toUtf8().data();
    }

    static void printQString(std::basic_ostringstream<wchar_t> &c, const QString &s) {
        std::wstring str;
        QStringToStdWString(s, str);
        c << L" " << str;
    }
};

#endif // TEXTLINECOMPOSER_H
